<template>
  <view class="my-approval">
    <!-- 搜索和筛选区域 -->
    <view class="search-section">
      <view class="search-box">
        <uni-icons type="search" size="18" color="#999"></uni-icons>
        <input class="search-input" placeholder="搜索申请标题或申请人" v-model="searchKeyword" @input="handleSearch" />
      </view>
    </view>

    <!-- 审批列表 -->
    <view class="approval-list">
      <view v-if="loading" class="loading">
        <uni-load-more status="loading"></uni-load-more>
      </view>

      <view v-else-if="filteredTasks.length === 0" class="empty-state">
        <image src="/static/workOverTime/empty-approval.png" class="empty-image"></image>
        <text class="empty-text">暂无待审批申请</text>
      </view>

      <view v-else>
        <view v-for="(task, index) in filteredTasks" :key="task.taskId" class="approval-card">
          <!-- 卡片头部 -->
          <view class="card-header">
            <view class="task-title">{{ task.title }}</view>
            <view class="task-status pending">待审批</view>
          </view>

          <!-- 申请信息 -->
          <view class="task-info">
            <view class="info-item">
              <uni-icons type="person" size="16" color="#666"></uni-icons>
              <text class="info-label">申请人：</text>
              <text class="info-value">{{ task.applicant }}</text>
            </view>
            <view class="info-item">
              <uni-icons type="calendar" size="16" color="#666"></uni-icons>
              <text class="info-label">开始时间：</text>
              <text class="info-value">{{ formatDate(task.startTime) }}</text>
            </view>
            <view class="info-item">
              <uni-icons type="calendar" size="16" color="#666"></uni-icons>
              <text class="info-label">结束时间：</text>
              <text class="info-value">{{ formatDate(task.endTime) }}</text>
            </view>
            <view class="info-item">
              <uni-icons type="list" size="16" color="#666"></uni-icons>
              <text class="info-label">审批环节：</text>
              <text class="info-value task-name">{{ task.taskName }}</text>
            </view>
          </view>

          <!-- 申请说明 -->
          <view class="task-explain" v-if="task.explain">
            <text class="explain-label">申请说明：</text>
            <text class="explain-content">{{ task.explain }}</text>
          </view>

          <!-- 操作按钮 -->
          <view class="action-buttons">
            <button class="btn reject-btn" @tap="handleReject(task)">
              <uni-icons type="close" size="16" color="#fff"></uni-icons>
              拒绝
            </button>
            <button class="btn approve-btn" @tap="handleApprove(task)">
              <uni-icons type="checkmark" size="16" color="#fff"></uni-icons>
              同意
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 自定义审批弹窗 -->
    <uni-popup ref="approvalPopup" type="bottom" safe-area>
      <view class="popup-custom">
        <view class="popup-header">
          <text class="popup-title">{{ popupTitle }}</text>
          <view class="popup-close" @tap="closePopup">
            <uni-icons type="closeempty" size="24" color="#999"></uni-icons>
          </view>
        </view>
        <view class="popup-body">
          <textarea
              v-model="approvalComment"
              :placeholder="popupPlaceholder"
              class="comment-input"
              maxlength="200"
              :adjust-position="false"
          />
        </view>
        <view class="popup-footer">
          <button class="btn cancel-btn" @tap="closePopup">取消</button>
          <button class="btn confirm-btn" @tap="confirmApproval">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { post } from '@/api/request.js'

export default {
  data() {
    return {
      tasks: [],
      loading: false,
      searchKeyword: '',
      currentTask: null,
      popupType: '', // 不再用于图标，仅逻辑判断
      popupTitle: '',
      popupPlaceholder: '请输入审批意见（选填）',
      approvalComment: ''
    }
  },
  computed: {
    filteredTasks() {
      if (!this.searchKeyword) {
        return this.tasks
      }
      const keyword = this.searchKeyword.toLowerCase()
      return this.tasks.filter(task =>
          task.title.toLowerCase().includes(keyword) ||
          task.applicant.toLowerCase().includes(keyword) ||
          (task.explain && task.explain.toLowerCase().includes(keyword))
      )
    }
  },
  mounted() {
    this.getTasks()
  },
  methods: {
    async getTasks() {
      this.loading = true
      try {
        const username = uni.getStorageSync('username')
        const res = await post('/zhy/getTasks', { username })
        if (res.code === 200 && res.data) {
          this.tasks = res.data
        } else {
          uni.showToast({ title: '获取审批任务失败', icon: 'none' })
        }
      } catch (error) {
        console.error('获取审批任务失败:', error)
        uni.showToast({ title: '网络错误，请重试', icon: 'none' })
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      // computed 已处理
    },

    formatDate(dateString) {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleDateString() + ' ' + date.toLocaleTimeString().slice(0, 5)
    },

    handleApprove(task) {
      this.currentTask = task
      this.popupTitle = '同意审批'
      this.popupPlaceholder = '请输入审批意见（选填）'
      this.approvalComment = ''
      this.$refs.approvalPopup.open()
    },

    handleReject(task) {
      this.currentTask = task
      this.popupTitle = '拒绝审批'
      this.popupPlaceholder = '请说明拒绝理由'
      this.approvalComment = ''
      this.$refs.approvalPopup.open()
    },

    async confirmApproval() {
      console.log('审批意见内容:', this.approvalComment) // ✅ 现在一定能打印出内容

      const isApprove = this.popupTitle === '同意审批'

      try {
        const res = await this.submitApproval(this.currentTask.taskId, isApprove, this.approvalComment,this.currentTask.taskName,this.currentTask.businessTaskId)

        if (res.code === 200) {
          uni.showToast({
            title: isApprove ? '审批通过' : '审批拒绝',
            icon: 'success'
          })
          // 从列表中移除已处理任务
          this.tasks = this.tasks.filter(task => task.taskId !== this.currentTask.taskId)
        } else {
          uni.showToast({ title: '审批操作失败', icon: 'none' })
        }
      } catch (error) {
        console.error('审批操作失败:', error)
        uni.showToast({ title: '操作失败，请重试', icon: 'none' })
      } finally {
        this.closePopup()
      }
    },

    async submitApproval(taskId, isApprove, comment,taskName,businessTaskId) {
      return await post('/zhy/approveTask', {
        taskId,
        approve: isApprove,
        comment: comment || '', // 确保为字符串
        taskName:taskName,
        businessTaskId:businessTaskId
      })
    },

    closePopup() {
      this.currentTask = null
      this.$refs.approvalPopup.close()
    }
  }
}
</script>

<style scoped>
.my-approval {
  padding: 20rpx;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.search-section {
  margin-bottom: 20rpx;
}

.search-box {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 50rpx;
  padding: 20rpx 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.search-input {
  flex: 1;
  margin-left: 20rpx;
  font-size: 28rpx;
}

.approval-list {
  margin-top: 20rpx;
}

.approval-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.task-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
}

.task-status {
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: bold;
}

.task-status.pending {
  background: #fff3cd;
  color: #856404;
}

.task-info {
  margin-bottom: 20rpx;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
  font-size: 28rpx;
}

.info-label {
  color: #666;
  margin: 0 10rpx 0 15rpx;
}

.info-value {
  color: #333;
  flex: 1;
}

.task-name {
  color: #007bff;
  font-weight: bold;
}

.task-explain {
  background: #f8f9fa;
  padding: 20rpx;
  border-radius: 10rpx;
  margin-bottom: 30rpx;
}

.explain-label {
  color: #666;
  font-size: 26rpx;
}

.explain-content {
  color: #333;
  font-size: 28rpx;
  line-height: 1.5;
}

.action-buttons {
  display: flex;
  gap: 20rpx;
}

.btn {
  flex: 1;
  height: 80rpx;
  border: none;
  border-radius: 40rpx;
  font-size: 28rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
}

.reject-btn {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  color: white;
}

.approve-btn {
  background: linear-gradient(135deg, #51cf66, #40c057);
  color: white;
}

.empty-state {
  text-align: center;
  padding: 100rpx 0;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
  opacity: 0.5;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
}

.loading {
  text-align: center;
  padding: 100rpx 0;
}

/* 自定义弹窗样式 */
.popup-custom {
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 40rpx 30rpx;
  min-height: 400rpx;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-close {
  padding: 10rpx;
}

.comment-input {
  width: 100%;
  height: 200rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
  box-sizing: border-box;
  line-height: 1.4;
}

.popup-footer {
  display: flex;
  gap: 20rpx;
}

.cancel-btn {
  flex: 1;
  height: 80rpx;
  background: #e9ecef;
  color: #666;
  border: none;
  border-radius: 40rpx;
  font-size: 28rpx;
  font-weight: bold;
}

.confirm-btn {
  flex: 1;
  height: 80rpx;
  background: linear-gradient(135deg, #51cf66, #40c057);
  color: white;
  border: none;
  border-radius: 40rpx;
  font-size: 28rpx;
  font-weight: bold;
}
</style>